package com.book.util;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Properties;

import javax.sql.DataSource;

import org.apache.commons.dbcp.BasicDataSourceFactory;

public class DBUtil {
	private static Properties pro = new Properties();
	private static ThreadLocal<Connection> myLocal = new ThreadLocal<Connection>();
	static{
		InputStream in =null;
		try{
		    in= DBUtil.class.getResourceAsStream("jdbc.properties");
			pro.load(in);
		} catch (IOException e) {
			e.printStackTrace();
		} finally{
				try {
					if(in !=null)
					in.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
	}
	public static Connection getConn() throws Exception{
		Connection conn = myLocal.get();
		if(conn==null){
			DataSource ds = BasicDataSourceFactory.createDataSource(pro);
			conn = ds.getConnection();
			myLocal.set(conn);
		}
		return conn;
	}
	public static void closeConn() throws SQLException{
		Connection conn = myLocal.get();
		if(conn!=null && !conn.isClosed()){
			conn.close();
			myLocal.remove();
		}
	}
	static PreparedStatement ps=null;
	//增加方法
	public static int add(String sql, ArrayList<Object> param){
		 int a = 0;
		 Connection conn=null;
		 try {
			conn=DBUtil.getConn();
			ps=conn.prepareStatement(sql);
			for (int i = 0; i < param.size(); i++) {
				ps.setObject(i+1, param.get(i));
				
			}
			a = ps.executeUpdate();
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			try {
				if(ps!=null)ps.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
			try {
				closeConn();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		 return a;
	}
	//删除方法
	public static int del(String sql, ArrayList<Object> param){
		return add(sql, param);
	}
	//修改方法
	public static int update(String sql, ArrayList<Object> param){
		return add(sql, param);
	}
}



